<template>
  <ElSpace>
    <viewImage
      v-if="isImage && modelValue"
      width="70px"
      height="70px"
      :src="modelValue"
      :previewList="[modelValue]"
      @contextmenu.stop.prevent="handleRightClickMenu"
    ></viewImage>
    <ElButton type="primary" @click="handleChoiceImage" :disabled="loading">
      {{ loading ? `上传中${progress}%` : "选择图片" }}
    </ElButton>
  </ElSpace>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ElSpace, ElButton, ElMessage } from "element-plus";
import viewImage from "@/components/image.vue";
import rightClickMenu from "@/library/rightClickMenu";
import { choiceFile } from "@/utils";
import ajax from "@/ajax";

const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  isImage: {
    type: Boolean,
    default: true,
  },
  isRemove: {
    type: Boolean,
    default: false,
  },
});

const loading = ref(false);
const progress = ref(0);

const handleRightClickMenu = function (event: MouseEvent) {
  if (!props.isRemove) return;
  if (!props.isImage) return;
  if (!props.modelValue) return;
  rightClickMenu(event, [
    {
      label: "删除",
      type: "danger",
      click() {
        emit("update:modelValue", "");
      },
    },
  ]);
};

const handleChoiceImage = function () {
  if (loading.value) return;
  choiceFile("image").then(function (file) {
    loading.value = true;
    progress.value = 0;
    ajax
      .upload(file[0], function (event: any) {
        progress.value = Math.ceil((event.loaded * 100) / event.total);
      })
      .then(function (res) {
        loading.value = false;
        if (res.code !== 200) {
          emit("update:modelValue", "");
          ElMessage.error(res.msg);
          return;
        }
        ElMessage.success("上传成功");
        emit("update:modelValue", res.fileName);
      });
  });
};
</script>
